/* Copyright (C) 2007 Free Software Foundation, Inc. 
 * See the copyright notice in the file /usr/LICENSE.
 * Created by flyan on 2020/5/25.
 * QQ: 1341662010
 * QQ-Group:909830414
 * gitee: https://gitee.com/flyanh/
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

static char * convert(char *s, int numRows){
    if(numRows == 1) return s;
    static char ans[1024] = { 0 };
    int fetch_len = 0, ssize = strlen(s);
    int single_cols = numRows - 2;   /* 先得到单列 */
    int i = 0, j = 0;
    int row_tag = 0;
    char *ap = ans;

    /* 根据行数初始化 */
    char *rows[numRows];
    int rows_len[numRows];
    for(i = 0; i < numRows; ++i) {
        rows[i] = (char *) malloc(ssize);
        rows_len[i] = 0;
    }

    while (fetch_len < ssize) {
        /* 首选正序输出 0~numRows 行 */
        row_tag = 0;
        for (i = numRows; i > 0 ; --i) {
            *(rows[row_tag] + rows_len[row_tag]++) = *(s + fetch_len++);
            row_tag++;
            if(fetch_len >= ssize) goto END;
        }
        /* 接着反向输出 single_cols 行 */
        row_tag = numRows - 1;
        for (j = single_cols; j > 0; --j) {
            row_tag--;
            *(rows[row_tag] + rows_len[row_tag]++) = *(s + fetch_len++);
            if(fetch_len >= ssize) goto END;
        }
    }
END:

    for(i = 0; i < numRows; ++i) {
        memcpy(ap, rows[i], rows_len[i]);
        ap += rows_len[i];
    }
    *ap = 0;
    return ans;
}

int main(void) {


    char *str2 = "PAYPALISHIRING";
    char *ans2 = convert(str2, 3);
    printf("answer: %s\n", ans2);
    return 0;
}

